package com.chidopi.market.bookstore.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.chidopi.cdf.service.impl.CommonServiceImpl;
import com.chidopi.market.bookstore.domain.BookZipBackup;
import com.chidopi.market.bookstore.service.IBookZipBackupService;

public class BookZipBackupServiceImpl extends CommonServiceImpl implements IBookZipBackupService {

	@Override
	public List<Map<String, Object>> getBookItemsList() throws Exception {
		String sql = "select ID, BOOKNAME from bookitems where ID in (select distinct BOOK_ID from bookzipbackup) order by ID";
		return super.queryForList(sql);
	}

	@Override
	public List<BookZipBackup> getBackupList(String sqlWhere, Object... args)
			throws Exception {
		
		String sql = "select a.*, b.BOOKNAME BOOKNAME from bookzipbackup a, bookitems b where ";
		if(sqlWhere ==null || sqlWhere.trim().length() == 0){
			sql += " a.BOOK_ID = b.id  order by a.BOOK_ID, CREATE_TIME ";			
		}else{
			sql +=  sqlWhere + " AND "  + "  a.BOOK_ID = b.id order by a.BOOK_ID, CREATE_TIME ";			
		}
		
		logger.debug("select sql: " + sql);
		
		List<Map<String, Object>> list  = super.queryForList(sql, args);
		
		return changeMapToBackup(list);
	}

	private List<BookZipBackup> changeMapToBackup(List<Map<String, Object>> list) {
		List<BookZipBackup>backups = null;
		if(list != null){
			backups = new ArrayList<BookZipBackup>();
			for(Map<String, Object> map:list){
				logger.debug("backup: " + map);
				BookZipBackup backup =new BookZipBackup(map);
				backups.add(backup);
			}
		}
		return backups;
	}

	@Override
	public BookZipBackup findByZipfile(Object zipfile) throws Exception {
		String sql = "select * from bookzipbackup where ZIPFILE = ?";
		List<Map<String, Object>> list = super.queryForList(sql, zipfile);
		if(list == null || list.isEmpty())
		    return null;
		BookZipBackup backup = new BookZipBackup(list.get(0));
		return backup;
	}

	@Override
	public int deleteBackup(BookZipBackup backup) throws Exception {
		
		String sql = "delete from bookzipbackup where ZIPFILE = ?";
		
		return super.commonDao.executeSQL(sql, backup.getZipfile());		
	}
}
